﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Security;
using System.Globalization;

namespace PasswordProvider.View.Library
{
    /// <summary>
    /// Interaction logic for PasswordGeneratorControl.xaml
    /// </summary>
    public sealed partial class PasswordGeneratorControl : UserControl
    {
        public PasswordGeneratorControl()
        {
            InitializeComponent();
        }

        #region Dependency Properties

        /// <summary>
        /// Dependency Property: GeneratedPasswordProperty
        /// </summary>
        public static readonly DependencyProperty GeneratedPasswordProperty =
           DependencyProperty.Register("GeneratedPassword", typeof(string), typeof(PasswordGeneratorControl));
        /// <summary>
        /// Get or set the generated password. This is a dependency property.
        /// </summary>
        public string GeneratedPassword
        {
            get { return (string)GetValue(GeneratedPasswordProperty); }
            set { SetValue(GeneratedPasswordProperty, value); }
        }

        #endregion

        #region Private

        private void _buttonDoGeneration_Click(object sender, RoutedEventArgs e)
        {
            string password = GeneratePassword();
            GeneratedPassword = password; 
        }

        private string GeneratePassword()
        {
            const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            const string digits = "1234567890";
            const string punct = ",.?:;\"'!`";
            const string symbols = "@#$%^&*_-+=<>/\\|}{[]()";

            string choseFrom = letters;
            if ((bool)_chkBoxDigits.IsChecked)
                choseFrom += digits;
            if ((bool)_chkBoxPunct.IsChecked)
                choseFrom += punct;
            if ((bool)_chkBoxSymbols.IsChecked)
                choseFrom += symbols;

            Random random = new Random((int)(DateTime.Now.Ticks));
            string val = (_comboBoxLength.SelectedItem as ComboBoxItem).Content as string;
            int length = int.Parse(val, CultureInfo.InvariantCulture);

            StringBuilder password = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                int index = random.Next(0, choseFrom.Length);
                password.Append(choseFrom[index]);
            }

            return password.ToString();
        }

        #endregion

    }
}
